from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.http import JsonResponse
from .models import CustomUser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime, timedelta
import jwt
from django.conf import settings
from rest_framework.decorators import authentication_classes, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.authentication import SessionAuthentication  # 添加这行

class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        email = request.data.get('email')
        password = request.data.get('password')
        if CustomUser.objects.filter(email=email).exists():
            return Response({'message': '邮箱已被注册'}, status=status.HTTP_400_BAD_REQUEST)
        if CustomUser.objects.filter(username=username).exists():
            return Response({'message': '用户名已被注册'}, status=status.HTTP_400_BAD_REQUEST)

        user = CustomUser(
            username=username,
            email=email,
            password=make_password(password)
        )
        user.save()
        return Response({'message': '注册成功'}, status=status.HTTP_201_CREATED)

class LoginView(APIView):
    def post(self, request):
        email = request.data.get('email')
        password = request.data.get('password')
        
        # 先通过邮箱查找用户
        try:
            user = CustomUser.objects.get(email=email)
        except CustomUser.DoesNotExist:
            return Response({'message': '邮箱或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)
        
        # 验证密码
        user = authenticate(request, username=user.username, password=password)
        
        if user is not None:
            login(request, user)
            payload = {
                'user_id': user.id,
                'exp': datetime.utcnow() + timedelta(days=7),
                'iat': datetime.utcnow()
            }
            token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
            
            response = Response({
                'message': '登录成功',
                'username': user.username,  # 添加用户名
                'role': user.role           # 添加角色
            })
            response.set_cookie(
                key='jwt_token',
                value=token,
                httponly=True,
                max_age=60*60*24*7,
                secure=True,
                samesite='Lax'
            )
            return response
        else:
            return Response({'message': '邮箱或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)

class LogoutView(APIView):
    authentication_classes = []  # 禁用所有认证
    permission_classes = [AllowAny]  # 允许所有访问
    
    def post(self, request):
        logout(request)
        response = Response({'message': '登出成功'}, status=status.HTTP_200_OK)
        response.delete_cookie('jwt_token')
        return response


class VerifyLoginView(APIView):
    def get(self, request):
        if request.user.is_authenticated:
            return Response({
                'isLoggedIn': True,
                'username': request.user.username,
                'role': request.user.role
            })
        return Response({'isLoggedIn': False})


class ProfileView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]  # 允许所有访问

    def post(self, request):
        username = request.data.get('originalUsername')  # 前端传原始用户名
        print(username)
        try:
            user = CustomUser.objects.get(username=username)
        except CustomUser.DoesNotExist:
            return Response({'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)

        old_password = request.data.get('oldPassword')
        new_password = request.data.get('newPassword')
        new_username = request.data.get('username')  # 新用户名参数改名
        
        # 验证原密码
        if not user.check_password(old_password):
            return Response({'message': '原密码错误'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 更新用户名
        if new_username and new_username != user.username:
            if CustomUser.objects.filter(username=new_username).exists():
                return Response({'message': '用户名已存在'}, status=status.HTTP_400_BAD_REQUEST)
            user.username = new_username
        
        # 更新密码
        if new_password:
            user.set_password(new_password)
        
        user.save()
        
        # 生成新的token返回给客户端
        payload = {
            'user_id': user.id,
            'exp': datetime.utcnow() + timedelta(days=7),
            'iat': datetime.utcnow()
        }
        token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        
        response = Response({'message': '修改成功'})
        response.set_cookie(
            key='jwt_token',
            value=token,
            httponly=True,
            max_age=60*60*24*7,
            secure=True,
            samesite='Lax'
        )
        
        return response